<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Elliptical Rotating Navigation</title>
  <style>
    #navContainer {
      position: relative;
      width: 300px;
      height: 200px;
      margin: 50px auto;
    }
    .navItem {
      position: absolute;
      width: 50px;
      height: 50px;
      background-color: lightblue;
      border-radius: 50%;
      text-align: center;
      line-height: 50px;
      cursor: pointer;
      transition: transform 0.5s ease;
    }
  </style>
</head>
<body>
  <div id="navContainer"></div>

  <script>
    const navContainer = document.getElementById('navContainer');
    const navItems = ['A', 'B', 'C', 'D', 'E'];
    const angleRange = [0, 180]; // 定义夹角范围
    const radiusX = 150; // 椭圆的X半径
    const radiusY = 100; // 椭圆的Y半径
    let currentIndex = 0;

    function createNavItems() {
      navItems.forEach((item, index) => {
        const navElement = document.createElement('div');
        navElement.className = 'navItem';
        navElement.innerText = item;
        navElement.onclick = () => rotateToIndex(index);
        navContainer.appendChild(navElement);
      });
      positionNavItems();
    }

    function positionNavItems() {
      const totalItems = navItems.length;
      const angleStep = (angleRange[1] - angleRange[0]) / (totalItems - 1);
      navContainer.childNodes.forEach((navElement, index) => {
        const angle = angleRange[0] + index * angleStep;
        const radian = angle * (Math.PI / 180);
        const x = radiusX * Math.cos(radian) - 25; // 25是navItem宽度的一半
        const y = radiusY * Math.sin(radian) - 25; // 25是navItem高度的一半
        navElement.style.transform = `translate(${x}px, ${y}px)`;
      });
    }

    let angleOffset = 0;
    function rotateToIndex(index) {
      let navStep = currentIndex - index; // 计算旋转步数
      currentIndex = index;
      angleOffset += navStep * ((angleRange[1] - angleRange[0]) / (navItems.length - 1));
      navContainer.childNodes.forEach((navElement, i) => {
        const angle = angleRange[0] + i * ((angleRange[1] - angleRange[0]) / (navItems.length - 1)) + angleOffset;
        const radian = angle * (Math.PI / 180);
        const x = radiusX * Math.cos(radian) - 25;
        const y = radiusY * Math.sin(radian) - 25;
        navElement.style.transform = `translate(${x}px, ${y}px)`;
      });
    }

    /** 
     *  解析transform字符串，返回x和y的数值
     */
    function getTranslateXAndY(translate){
      let reg = /-?\d+(\.\d+)?/g; // 支持负数和小数
      const [x, y] = translate.match(reg).map(Number);
      return { x, y };
    }

    createNavItems();
  </script>
</body>
</html>